<?php

namespace app\admin\controller\knowbase;

use app\common\controller\Backend;
use app\common\model\knowbase\AuthAccess;
use app\common\model\knowbase\AuthGroupAccess;
use fast\Tree;
use think\exception\PDOException;
use think\Exception;
use think\exception\DbException;
use think\exception\ValidateException;
use think\Loader;
use think\Db;
use think\response\Json;

/**
 * 知识库项目
 *
 * @icon fa fa-circle-o
 */
class Project extends Backend
{

    /**
     * Project模型对象
     * @var \app\common\model\knowbase\Project
     */
    protected $model = null;
    protected $modelValidate  = true;
    protected $relationSearch = true;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\knowbase\Project;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("accessTypeList", $this->model->getAccessTypeList());
    }

    /**
     * 克隆项目
     * @param $ids
     * @throws DbException
     */
    public function cloneone($ids){
        
        if (!$this->model->cloneone($ids)){
            $this->error($this->model->getError());
        }
        $this->success();
    }

    /**
     * 导出网站地图
     */
    public function sitemap(){
        $header_file = ADDON_PATH . 'knowbase' . DS.'sitemap.xsl';
        $url_file = ADDON_PATH . 'knowbase' . DS.'sitemap.xml';
        if (!is_file($header_file) || !is_file($url_file)) {
             $this->error('丢失模板文件');
        }
        $public_path = ROOT_PATH . 'public' . DS;
        if (!is_writable($public_path)) {
             $this->error('网站目录不可写，请先修改目录权限');
        }
        $header_content = file_get_contents($header_file);
        $header_content = str_replace('[name]', config('site.name'), $header_content);
        $url_content = file_get_contents($url_file);
        $str = '';
        $data = \app\common\model\knowbase\Project::getHotPages();
        foreach ($data as $v){
            $str.= sprintf('<url><loc>%s</loc><lastmod>%s</lastmod></url>',$v['url'],$v['time']);
        }
        $url_content = str_replace('[str]', $str, $url_content);
        file_put_contents($public_path.'sitemap.xsl', $header_content);
        file_put_contents($public_path.'sitemap.xml', $url_content);
        \app\common\model\knowbase\Progress::addLog('sitemap',0);
        $this->success('ok');
    }
    
    /**
     * 导出HTML
     */
    public function export_html() {
        $project_id = $this->request->param('knowbase_project_id',0,'intval');
        $project = \app\common\model\knowbase\Project::get($project_id);
        if (!$project->checkAccess()) {
            $this->error(__('tips_not_access'));
        }
        if (request()->isPost()){
            \app\common\model\knowbase\Progress::addLog('project_html',$project_id);
            $this->success('ok');
        }
        $model = new \app\common\model\knowbase\ProjectPage();
        $list = collection($model->field('id,deep,pid,type,title,content')->where('knowbase_project_id',$project_id)->where('status_switch',1)->order('weigh DESC,id ASC')->select())->toArray();
        $parentList = knowbase_groupsbyid(array_map(function ($v){
            return ['id'=>$v['id'],'pid'=>$v['pid']];
        }, $list),'pid');
        Tree::instance()->init($list)->icon = ['&nbsp;&nbsp;&nbsp;&nbsp;', '&nbsp;&nbsp;&nbsp;&nbsp;', '&nbsp;&nbsp;&nbsp;&nbsp;'];
        $list = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0), 'title');
       
        $content = '';
        foreach ($list as &$v) {
            if ($v['type']=='dir' && (empty($parentList[$v['id']]) || count($parentList[$v['id']])==0)) {
               
                $v['type']='file';
            }
           
            $content.=knowbase_replace_content_title_level($v);
            unset($v);
        }
        unset($list);
        $this->assign('content',$content);
        return $this->view->fetch();
    }
    
    /**
     * 导出PDF
     */
    public function export() {
        $project_id = $this->request->param('knowbase_project_id',0,'intval');
        $project = \app\common\model\knowbase\Project::get($project_id);
        if (!$project->checkAccess()) {
            $this->error(__('tips_not_access'));
        }
        if (request()->isPost()){
            \app\common\model\knowbase\Progress::addLog('project_pdf',$project_id);
            $this->success('ok');
        }
        $model = new \app\common\model\knowbase\ProjectPage();
        $list = collection($model->field('id,deep,pid,type,title,content')->where('knowbase_project_id',$project_id)->where('status_switch',1)->order('weigh DESC,id ASC')->select())->toArray();
        $parentList = knowbase_groupsbyid(array_map(function ($v){
            return ['id'=>$v['id'],'pid'=>$v['pid']];
        }, $list),'pid');
        Tree::instance()->init($list)->icon = ['&nbsp;&nbsp;&nbsp;&nbsp;', '&nbsp;&nbsp;&nbsp;&nbsp;', '&nbsp;&nbsp;&nbsp;&nbsp;'];
        $list = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0), 'title');
       
        $content = '';
        foreach ($list as &$v) {
            if ($v['type']=='dir' && (empty($parentList[$v['id']]) || count($parentList[$v['id']])==0)) {
               
                $v['type']='file';
            }
           
            $content.=knowbase_replace_content_title_level($v);
            unset($v);
        }
        unset($list);
        $this->assign('content',$content);
        return $this->view->fetch();
    }
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    
    /**
     * 真实删除
     *
     * @param $ids
     * @return void
     */
    public function destroy($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post('ids');
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        if ($ids) {
            $this->model->where($pk, 'in', $ids);
        }
        $count = 0;
        Db::startTrans();
        try {
            $list = $this->model->onlyTrashed()->select();
            foreach ($list as $item) {
                if (!$item->checkAccess()) {
                    $this->error(__('tips_not_access'));
                }
                \app\common\model\knowbase\ProjectPage::useGlobalScope(false)->whereIn('knowbase_project_id',$item['id'])->delete(true);
                $count += $item->delete(true);
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
       
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            $this->assignconfig('clone', $this->auth->check('knowbase/project/cloneone'));  
            $this->assignconfig('url_knowbase_project',config('url_knowbase_project')); 
            return $this->view->fetch();
        }
       
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->with(['admin'=>function($query){
                return $query->withField('id,username');
            },'groups'=>function($query){
                return $query->with(['authGroup'=>function($q){
                    return $q->withField('id,name');
                }]);
            },'auths'=>function($query){
                return $query->with(['auth'=>function($q){
                    return $q->withField('id,username');
                }]);
            }])
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        foreach ($list as $v){
            $groups = [];
            $auths = [];
            foreach ($v['groups'] as $vv) {
                $groups[] = str_replace("&nbsp;", '', strip_tags($vv['auth_group']['name']));
            }
            $v['groups_tags'] = implode(",", $groups);

            foreach ($v['auths'] as $vv) {
                $auths[] = str_replace("&nbsp;", '', strip_tags($vv['auth']['username']));
            }
            $v['auth_tags'] = implode(",", $auths);

        }
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * 生成查询所需要的条件,排序方式
     * @param mixed   $searchfields   快速查询的字段
     * @param boolean $relationSearch 是否关联查询
     * @return array
     */
    protected function buildparams($searchfields = null, $relationSearch = null)
    {
        $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
        $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
        $search = $this->request->get("search", '');
        $filter = $this->request->get("filter", '');
        $op = $this->request->get("op", '', 'trim');
        $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
        $order = $this->request->get("order", "DESC");
        $offset = $this->request->get("offset/d", 0);
        $limit = $this->request->get("limit/d", 999999);
       
        $page = $limit ? intval($offset / $limit) + 1 : 1;
        if ($this->request->has("page")) {
            $page = $this->request->get("page/d", 1);
        }
        $this->request->get([config('paginate.var_page') => $page]);
        $filter = (array)json_decode($filter, true);
        $op = (array)json_decode($op, true);
        $filter = $filter ? $filter : [];
        $where = [];
        $alias = [];
        $bind = [];
        $name = '';
        $aliasName = '';
        if (!empty($this->model) && $relationSearch) {
            $name = $this->model->getTable();
            $alias[$name] = Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
            $aliasName = $alias[$name] . '.';
        }
        $sortArr = explode(',', $sort);
        foreach ($sortArr as $index => & $item) {
            $item = stripos($item, ".") === false ? $aliasName . trim($item) : $item;
        }
        unset($item);
        $sort = implode(',', $sortArr);
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $where[] = [$aliasName . $this->dataLimitField, 'in', $adminIds];
        }
        if ($search) {
            $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
            foreach ($searcharr as $k => &$v) {
                $v = stripos($v, ".") === false ? $aliasName . $v : $v;
            }
            unset($v);
            $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
        }
        $index = 0;
        foreach ($filter as $k => $v) {
            if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', $k)) {
                continue;
            }
            $sym = $op[$k] ?? '=';
            if (stripos($k, ".") === false) {
                $k = $aliasName . $k;
            }
            $v = !is_array($v) ? trim($v) : $v;
            $sym = strtoupper($op[$k] ?? $sym);
           
            if (!is_array($v)) {
                if (in_array(strtoupper($v), ['NULL', 'NOT NULL'])) {
                    $sym = strtoupper($v);
                }
                if (in_array($v, ['""', "''"])) {
                    $v = '';
                    $sym = '=';
                }
            }

            switch ($sym) {
                case '=':
                case '<>':
                    $where[] = [$k, $sym, (string)$v];
                    break;
                case 'LIKE':
                case 'NOT LIKE':
                case 'LIKE %...%':
                case 'NOT LIKE %...%':
                    $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
                    break;
                case '>':
                case '>=':
                case '<':
                case '<=':
                    $where[] = [$k, $sym, intval($v)];
                    break;
                case 'FINDIN':
                case 'FINDINSET':
                case 'FIND_IN_SET':
                    $v = is_array($v) ? $v : explode(',', str_replace(' ', ',', $v));
                    $findArr = array_values($v);
                    foreach ($findArr as $idx => $item) {
                        $bindName = "item_" . $index . "_" . $idx;
                        $bind[$bindName] = $item;
                        $where[] = "FIND_IN_SET(:{$bindName}, `" . str_replace('.', '`.`', $k) . "`)";
                    }
                    break;
                case 'IN':
                case 'IN(...)':
                case 'NOT IN':
                case 'NOT IN(...)':
                    $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
                    break;
                case 'BETWEEN':
                case 'NOT BETWEEN':
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr, function ($v) {
                        return $v != '' && $v !== false && $v !== null;
                    })) {
                        continue 2;
                    }
                   
                    if ($arr[0] === '') {
                        $sym = $sym == 'BETWEEN' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'BETWEEN' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, $sym, $arr];
                    break;
                case 'RANGE':
                case 'NOT RANGE':
                    $v = str_replace(' - ', ',', $v);
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr)) {
                        continue 2;
                    }
                   
                    if ($arr[0] === '') {
                        $sym = $sym == 'RANGE' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'RANGE' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $tableArr = explode('.', $k);
                    if (count($tableArr) > 1 && $tableArr[0] != $name && !in_array($tableArr[0], $alias)
                        && !empty($this->model) && $this->relationSearch) {
                       
                        $relation = Loader::parseName($tableArr[0], 1, false);
                        $alias[$this->model->$relation()->getTable()] = $tableArr[0];
                    }
                    $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' TIME', $arr];
                    break;
                case 'NULL':
                case 'IS NULL':
                case 'NOT NULL':
                case 'IS NOT NULL':
                    $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
                    break;
                default:
                    break;
            }
            $index++;
        }
        if (!empty($this->model)) {
            $this->model->alias($alias);
        }
        $model = $this->model;
        
       
        $hasProject = true;
        $filters = [];
        foreach ($where as $k=>$v) {
            if ($v[0]=='project.admin_ids' && $v[1]=='IN' && $hasProject) {
                $projects = array_column(
                    collection(AuthAccess::whereIn('uid',$v[2])
                   
                    ->field('project_id')
                    ->group('project_id')
                    ->having('count(*)='.count($v[2]))
                    ->select())->toArray()
                ,'project_id');
                $filters[] = ['name'=>$v[0],'data'=>$projects];
                if (!$projects) {
                    $hasProject = false;
                }
            }

            if ($v[0]=='project.auth_group_ids' && $v[1]=='IN' && $hasProject) {
                $filterFileds[] = $v[0];
                $projects = array_column(
                    collection(AuthGroupAccess::whereIn('group_id',$v[2])
                       
                        ->field('project_id')
                        ->group('project_id')
                        ->having('count(*)='.count($v[2]))
                        ->select())->toArray()
                    ,'project_id');
                $filters[] = ['name'=>$v[0],'data'=>$projects];
                if (!$projects) {
                    $hasProject = false;
                }
            }
        }

       
        if ($filters) {
            $where = array_values(array_filter($where,function ($v) use ($filters){
               foreach ($filters as $filter) {
                   if ($v[0][0]==$filter['name']) {
                       return true;
                   }
               }
                return false;
            }));

            $projects = $filters[0]['data'];
           
             foreach ($filters as $filter) {
                 $projects = array_values(array_intersect($projects, $filter['data']));
             }
             if ($projects) {
                $where[] = ['project.id','IN',$projects];
             } else {
                $where[] = ['project.id','=',9999999999];
             }

        }
       
        
       
        $projectIds = $this->getDataLimitProjectIds();
        if ($projectIds) {
            $where[] = ['project.id','IN',$projectIds];
        }
        
        $where = function ($query) use ($where, $alias, $bind, &$model) {
            if (!empty($model)) {
                $model->alias($alias);
                $model->bind($bind);
            }
            foreach ($where as $k => $v) {
                if (is_array($v)) {
                    call_user_func_array([$query, 'where'], $v);
                } else {
                    $query->where($v);
                }
            }
        };
        return [$where, $sort, $order, $offset, $limit, $page, $alias, $bind];
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
//            if (!$params['identify']) {
//                $params['identify'] = NULL;
//            }
//
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }
    
    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        try {
//            if (!$params['identify']) {
//                $params['identify'] = NULL;
//            }
            Db::startTrans();
           
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (\Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
    
    /**
     * 获取数据限制的项目ID列表
     * 禁用数据限制时返回的是null
     * @return mixed
     */
    protected function getDataLimitProjectIds()
    {
        if ($this->auth->isSuperAdmin()) {
            return null;
        }
        $groups = array_column($this->auth->getGroups(),'group_id');
       
        $groupProjects = array_column(collection(AuthGroupAccess::whereIn('group_id',$groups)
                    ->field('project_id')
                    ->select())
            ->toArray(),'project_id');
       
        $userProjects = array_column(collection(AuthAccess::where('uid',$this->auth->id)
                    ->field('project_id')
                    ->select())
            ->toArray(),'project_id');
        $prefix = config('database.prefix');
       
        $unUserProjects = array_column(Db::query("select p.id from {$prefix}knowbase_project p where  not exists (select 1 from {$prefix}knowbase_auth_access a where a.project_id=p.id)"),'id');
       
        $unGroupProjects = array_column(Db::query("select p.id from {$prefix}knowbase_project p where  not exists (select 1 from {$prefix}knowbase_auth_group_access a where a.project_id=p.id)"),'id');
        $result =  array_merge(array_merge($groupProjects, $userProjects),array_intersect($unUserProjects, $unGroupProjects));
        if (!$result) {
            $result = [KNOW_BASE_NONE];
        }
        return $result;
    }
    
}
